
import 'dart:math';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:ycbl/utils/resource_manager.dart';

/// 加载本地图片
class LocalImage extends StatelessWidget {

  final String imageName;
  final double width;
  final double height;
  final BoxFit fit;

  /// 加载本地图片
  const LocalImage(this.imageName, {this.width, this.height, this.fit});

  @override
  Widget build(BuildContext context) {

    var name = ResourceManager.wrapLocalImage(imageName);

    return Image.asset(name, width: width, height: height, fit: fit,);
  }
}

/// 加载网络图片，包装一层，方便统一修改，也可以直接使用 CachedNetworkImage
class BLNetworkImage extends StatelessWidget {

  final String url;
  final double width;
  final double height;
  final BoxFit fit;
  final Widget placeHolder;
  final Widget errWidget;

  const BLNetworkImage({
    Key key,
    @required this.url,
    this.width,
    this.height,
    this.fit = BoxFit.cover,
    this.placeHolder = const DefaultPlaceHolder(),
    this.errWidget = const DefaultPlaceHolder()
  }) : super(key: key);

  String get imageUrl => ResourceManager.wrapUrl(url);

  @override
  Widget build(BuildContext context) {
    return CachedNetworkImage(
      imageUrl: imageUrl,
      width: width,
      height: height,
      fit: fit,
      placeholder: (_, __) => placeHolder,
      errorWidget: (_, __,  ___) => errWidget,
    );
  }
}

/// 默认图片
class DefaultPlaceHolder extends StatelessWidget {

  /// 图片的宽
  final double imgWidth;
  /// 图片的高
  final double imgHeight;
  /// 使用转圈圈
  final bool useIndicator;

  /// 默认图片
  const DefaultPlaceHolder({Key key, this.imgWidth, this.imgHeight, this.useIndicator = false}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    if (useIndicator) {
      // 使用转圈圈
      var radius;
      // 宽高等于 0
      if (imgWidth == null || imgHeight == null) {
        radius = 12.0;
      }else {
        //为了避免转圈圈沾满整个 View ，除以 3
        radius = min(imgWidth, imgHeight) / 3.0;
      }

      return CupertinoActivityIndicator(radius: radius,);
    }else {
      //使用本地默认图片
      return LocalImage('img_default_pic.png', width: imgWidth, height: imgHeight, fit: BoxFit.cover,);
    }

  }
}



